﻿using DapperDB.Entities;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace TaskSchedul
{
    public class Run : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap data = context.JobDetail.JobDataMap;
            string id = data.GetString("TaskID");

            try
            {
                var job = new Task_JobDap().GetByKey(id);

                DateTime st = DateTime.Now;

                job.LastTime = st.ToString("yyyy-MM-dd hh:mm:ss");

                LoadAllPlugs(job.Job_DllPath);

                job.NextTime = Convert.ToDateTime(context.NextFireTimeUtc.ToString()).ToString("yyyy-MM-dd hh:mm:ss");

                DateTime end = DateTime.Now;

                job.ProcessTime = (int)(end - st).TotalSeconds;

                job.FunctionCount = job.FunctionCount + 1;

                new Task_JobDap().Update(job);
            }
            catch (Exception e)
            {
                ToolHelper.WriteLog("运行错误 TaskID:" + id, e.ToString());
            }
        }

        /// <summary>
        /// 载入所有插件
        /// </summary>
        private void LoadAllPlugs(string dllpath)
        {
            try
            {
                //载入dll
                Assembly ab = Assembly.LoadFrom(dllpath);
                Type[] types = ab.GetTypes();
                foreach (Type t in types)
                {
                    //如果某些类实现了预定义的ITask接口，则认为该类适配与主程序(是主程序的插件)
                    if (t.GetInterface("ITask") != null)
                    {
                        object selObj = ab.CreateInstance(t.FullName);
                        Type tt = selObj.GetType();
                        MethodInfo OnShowDlg = tt.GetMethod("Execute");
                        OnShowDlg.Invoke(selObj, null);
                    }
                }
            }
            catch (Exception ex)
            {
                ToolHelper.WriteLog("dll运行错误 dll:" + dllpath, ex.ToString());
            }


        }


    }
}